import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { removeEmptyValues } from "@/utils/common";
import {
  getAccountList,
  addAccount,
  activeAccount,
  archiveAccount,
  setAccountType,
  resetAccountPwd,
  updateAccount
} from "@/api/account";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import { usePublicHooks } from "@/views/system/hooks";

export function useAccount(treeRef: Ref) {
  const form = reactive({
    realName: null,
    accountName: null,
    accountStatus: null,
    accountType: null
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type:"index",
      width:60
    },
    {
      label: "账户ID",
      prop: "pid",
      hide: true
    },
    {
      label: "账户名称",
      prop: "realName"
    },
    {
      label: "登录名称",
      prop: "accountName"
    },
    {
      label: "所属租户",
      prop: "tenantName",
      minWidth: 160
    },
    {
      label: "备注",
      prop: "accountDesc",
      minWidth: 160
    },
    {
      label: "账户类型",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.accountType}
          active-value={0}
          inactive-value={1}
          active-text="普通用户"
          inactive-text="管理员"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChangeType(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.archiveStatus}
          active-value={"active"}
          inactive-value={"archive"}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChangeStatus(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];
  function onChangeStatus({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${row.archiveStatus === "archive" ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${row.realName
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        try {
          if (row.archiveStatus === "active") {
            await activeAccount(row.accountName);
          } else {
            await archiveAccount(row.accountName);
          }
          message(
            `已${row.archiveStatus === "archive" ? "停用" : "启用"}${row.realName}`,
            {
              type: "success"
            }
          );
        } catch (ERR) {
          message(
            `${row.archiveStatus === "archive" ? "停用" : "启用"}${row.realName}失败:${ERR.message}`,
            {
              type: "error"
            }
          );
        } finally {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          onRefash();
        }
      })
      .catch(() => {
        row.archiveStatus === "archive"
          ? (row.archiveStatus = "active")
          : (row.archiveStatus = "archive");
      });
  }
  function onChangeType({ row, index }) {
    ElMessageBox.confirm(
      `确认要设置<strong style='color:var(--el-color-primary)'>${row.realName
      }</strong><strong>为${row.accountType === 0 ? "普通用户" : "管理员"
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        try {
          await setAccountType({
            accountName: row.accountName,
            accountType: row.accountType
          });
          message(
            `已将${row.realName}设置为${row.accountType === 1 ? "管理员" : "普通用户"}`,
            {
              type: "success"
            }
          );
          onRefash();
        } catch (err) {
          message(
            `将${row.realName}设置为${row.accountType === 1 ? "管理员" : "普通用户"}失败：${err.message}`,
            {
              type: "error"
            }
          );
          row.accountType === 1 ? (row.accountType = 0) : (row.accountType = 1);
        } finally {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
        }
      })
      .catch(() => {
        row.accountType === 1 ? (row.accountType = 0) : (row.accountType = 1);
      });
  }

  function handleResetPwd(row) {
    resetAccountPwd(row)
      .then(function (data) {
        message(`账户${row.realName}的密码重置为：${data}`, {
          type: "success"
        });
      })
      .catch(function (err) {
        message(`账户${row.realName}的密码重置失败`, {
          type: "error"
        });
      });
  }
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    // loading.value = true;
    pagination.currentPage = val;
    onRefash();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  

  function mergedParams() {
    const data = {
      ...toRaw(form),
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    return removeEmptyValues(data);
  }

  async function onSearch() {
    loading.value = true;
    pagination.currentPage = 1;
    getAccountList(mergedParams()).then(function (data) {
      dataList.value = data.data.list;
      pagination.total = data.data.total;
      pagination.pageSize = data.data.pageSize;
      pagination.currentPage = data.data.currentPage;
      pagination.pageCount = data.data.totalPage;
    }).catch(function (err) {
      message(`账户清单加载异常：${err.message}`, {
        type: "error"
      });
    });
    loading.value = false;
  }

  async function onRefash() {
    loading.value = true;
    getAccountList(mergedParams()).then(function (data) {
      dataList.value = data.data.list;
      pagination.total = data.data.total;
      pagination.pageSize = data.data.pageSize;
      pagination.currentPage = data.data.currentPage;
      pagination.pageCount = data.data.totalPage;
    }).catch(function (err) {
      message(`账户清单加载异常：${err.message}`, {
        type: "error"
      });
    });
    loading.value = false;
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}账户`,
      props: {
        formInline: {
          realName: row?.realName ?? "",
          accountName: row?.accountName ?? "",
          accountDesc: row?.accountDesc ?? "",
          tenantName: row?.tenantName ?? "",
          accountType: row?.accountType ?? 0,
          editStatus: title == "新增" ? false : true
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: false,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了账户名称为${curData.realName}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              addAccount(curData)
                .then(function (data) {
                  chores();
                  onSearch(); // 刷新表格数据
                })
                .catch(function (err) {
                  message(`${title}账户失败:${err.message}`, {
                    type: "error"
                  });
                });
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              updateAccount(curData)
                .then(function (data) {
                  chores();
                  onRefash();
                })
                .catch(function (err) {
                  message(`${title}账户失败:${err.message}`, {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  /** 菜单权限 */
  async function handleMenu(row?: any) {
    const { pid } = row;
    if (pid) {
      curRow.value = row;
      isShow.value = true;
      // const { data } = await getRoleMenuIds({ id });
      // treeRef.value.setCheckedKeys(data);
    } else {
      curRow.value = null;
      isShow.value = false;
    }
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { pid } }) {
    return {
      cursor: "pointer",
      background: pid === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 菜单权限-保存 */
  function handleSave() {
    const { pid, name } = curRow.value;
    // 根据用户 id 调用实际项目中菜单权限修改接口
    console.log(pid, treeRef.value.getCheckedKeys());
    message(`账户名称为${name}的菜单权限修改成功`, {
      type: "success"
    });
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    // const { data } = await getRoleMenu();
    // treeIds.value = getKeyList(data, "id");
    // treeData.value = handleTree(data);
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    // buttonClass,
    onSearch,
    onRefash,
    resetForm,
    openDialog,
    handleMenu,
    handleSave,
    handleResetPwd,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
